﻿using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Gds.Utility.Helper
{
    public class DataBaseHelper
    {
        public static IMongoDatabase _database;
        public static IMongoDatabase _backupdatabase;
        public static IMongoClient _client;
        public static IMongoClient _backupclient;
        public static System.Net.Sockets.TcpClient dbCheck;
        public static string CollectionName = "EquipConfig";

        public static bool OpenDataBase(string ServerIp = "localhost")
        {
            bool result = true;
            try
            {
                string strCon = "mongodb://{0}:27017/GasData?maxPooSize=3000";
                strCon = string.Format(strCon, ServerIp);
                var mongoUrl = new MongoUrlBuilder(strCon)
                {
                    MaxConnectionPoolSize = 1000
                };
                string databaseName = mongoUrl.DatabaseName;
                _client = new MongoClient(mongoUrl.ToMongoUrl());
          
                _database = _client.GetDatabase(databaseName);
                //系统配置到时候保存在本地加载

                dbCheck = new System.Net.Sockets.TcpClient(ServerIp, 27017);
                Utility.Const.GbUnit.DatabaseLinkSuccessFlag = true;


            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("由于目标计算机积极拒绝") || ex.Message.Contains("失败"))
                {
                    PublicHelper.ShowLogMsg("由于目标计算机积极拒绝,数据库连接失败");
                    Utility.Const.GbUnit.DatabaseLinkSuccessFlag = false;
                }
                Utility.Helper.PublicHelper.WriteErrorMsg(ex);
                result = false;
            }
            return result;
        }
        public static bool linkBackUpServer(string ServerIp = "localhost")
        {
            bool result = true;
            try
            {
                string strCon = "mongodb://{0}:27017/GasData?maxPooSize=3000";
                strCon = string.Format(strCon, ServerIp);
                var mongoUrl = new MongoUrlBuilder(strCon)
                {
                    MaxConnectionPoolSize = 1000
                };
                string databaseName = mongoUrl.DatabaseName;
                _backupclient = new MongoClient(mongoUrl.ToMongoUrl());
               

                _backupdatabase = _backupclient.GetDatabase(databaseName);
                //系统配置到时候保存在本地加载
                dbCheck = new System.Net.Sockets.TcpClient(ServerIp, 27017);
                Utility.Const.GbUnit.BackupDatabaseLinkSuccessFlag = true;

                Const.GbUnit.IsContainBackUpServer = true;
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("由于目标计算机积极拒绝"))
                {
                    Utility.Const.GbUnit.BackupDatabaseLinkSuccessFlag = false;
                }
                Utility.Helper.PublicHelper.WriteErrorMsg(ex);
                result = false;
            }
            return result;
        }
        /// <summary>
        /// 查看数据库是否连接成功  成功 True  失败 false
        /// </summary>
        /// <returns></returns>
        public static bool CheckDBLinkState()
        {
            if (IsContainBackUp)
            {
                return !(Utility.Const.GbUnit.DatabaseLinkSuccessFlag == false && Const.GbUnit.BackupDatabaseLinkSuccessFlag == false);
            }
            else
            {
                return Utility.Const.GbUnit.DatabaseLinkSuccessFlag;
            }

        }
        /// <summary>
        /// 查看主要数据库是否连接成功  成功 True  失败 false
        /// </summary>
        /// <returns></returns>
        public static bool CheckMainDBLinkState()
        {
            return Utility.Const.GbUnit.DatabaseLinkSuccessFlag;
        }
        /// <summary>
        /// 查看备用数据库是否连接成功  成功 True  失败 false
        /// </summary>
        /// <returns></returns>
        public static bool CheckBackupDBLinkState()
        {
            return Utility.Const.GbUnit.BackupDatabaseLinkSuccessFlag;
        }
        /// <summary>
        /// 是否包含备用服务器
        /// </summary>
        public static bool IsContainBackUp { get { return Const.GbUnit.IsContainBackUpServer; } }
        #region Insert
        public static bool InserLogModel<T>(T insertModel)
        {
            if (CheckDBLinkState() == false)
            {
                return false;
            }
            bool result = true;
            try
            {
                BsonDocument tmpDoc = new BsonDocument();
                tmpDoc = insertModel.ToBsonDocument();

                if (CheckMainDBLinkState())
                {
                    var collectionTable = _database.GetCollection<BsonDocument>("LogMessage");
                    collectionTable.InsertOne(tmpDoc);
                }
                if (IsContainBackUp)
                {
                    if (CheckBackupDBLinkState())
                    {
                        tmpDoc = new BsonDocument();
                        tmpDoc = insertModel.ToBsonDocument();
                        var collectionTable_2 = _backupdatabase.GetCollection<BsonDocument>("LogMessage");
                        collectionTable_2.InsertOne(tmpDoc);
                    }
                }

            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    CheckIsTimeOut(ex.InnerException.Message);
                }
                PublicHelper.WriteErrorMsg(ex, "插入数据模型");


            }
            return result;
        }
        /// <summary>
        /// 插入一个模型到数据表中
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="insertModel"></param>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public static bool InserOneModel<T>(T insertModel, string tableName)
        {
            if (CheckDBLinkState() == false)
            {
                return false;
            }
            bool result = true;
            try
            {


                BsonDocument tmpDoc = new BsonDocument();
                tmpDoc = insertModel.ToBsonDocument();
                if (CheckMainDBLinkState())
                {
                    var collectionTable = _database.GetCollection<BsonDocument>(tableName);
                    collectionTable.InsertOne(tmpDoc);
                }
                if (IsContainBackUp)
                {
                    if (CheckBackupDBLinkState())
                    {
                        tmpDoc = new BsonDocument();
                        tmpDoc = insertModel.ToBsonDocument();
                        var collectionTable_2 = _backupdatabase.GetCollection<BsonDocument>(tableName);
                        collectionTable_2.InsertOne(tmpDoc);
                    }
                }


            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    CheckIsTimeOut(ex.InnerException.Message);
                }
                PublicHelper.WriteErrorMsg(ex, "插入数据模型");
            }
            return result;
        }
        /// <summary>
        /// 插入一个模型集合到数据表中 list
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="insertModelList"></param>
        /// <param name="InsertCollection"></param>
        /// <returns></returns>
        public static bool InsertModelList<T>(List<T> insertModelList, string InsertCollection)
        {
            if (CheckDBLinkState() == false)
            {
                return false;
            }
            bool result = true;
            try
            {

                if (CheckMainDBLinkState())
                {
                    var _collection = _database.GetCollection<BsonDocument>(InsertCollection);
                    var insertDoc = insertModelList.Select(x => x.ToBsonDocument());
                    _collection.InsertManyAsync(insertDoc);
                }
                if (IsContainBackUp)
                {
                    if (CheckBackupDBLinkState())
                    {
                        var _collection = _backupdatabase.GetCollection<BsonDocument>(InsertCollection);
                        var insertDoc = insertModelList.Select(x => x.ToBsonDocument());
                        _collection.InsertManyAsync(insertDoc);
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    CheckIsTimeOut(ex.InnerException.Message);
                }
                PublicHelper.WriteErrorMsg(ex, "插入数据模型集合");
                result = false;
            }
            return result;
        }
        /// <summary>
        /// 插入一个模型集合到数据表中 observable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="insertModelList"></param>
        /// <param name="InsertCollection"></param>
        /// <returns></returns>
        public static bool InsertModelList<T>(ObservableCollection<T> insertModelList, string InsertCollection)
        {
            if (CheckDBLinkState() == false)
            {
                return false;
            }
            bool result = true;
            try
            {

                if (CheckMainDBLinkState())
                {
                    var _collection = _database.GetCollection<BsonDocument>(InsertCollection);
                    var insertDoc = insertModelList.Select(x => x.ToBsonDocument());
                    _collection.InsertManyAsync(insertDoc);
                }
                if (IsContainBackUp)
                {
                    if (CheckBackupDBLinkState())
                    {
                        var _collection = _backupdatabase.GetCollection<BsonDocument>(InsertCollection);
                        var insertDoc = insertModelList.Select(x => x.ToBsonDocument());
                        _collection.InsertManyAsync(insertDoc);
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    CheckIsTimeOut(ex.InnerException.Message);
                }
                PublicHelper.WriteErrorMsg(ex, "插入数据模型集合");

                result = false;
            }
            return result;
        }
        #endregion
        #region Delete
        /// <summary>
        /// 删除一个表的数据 目前只用于删除系统配置
        /// </summary>
        /// <param name="CollectionName"></param>
        /// <returns></returns>
        public static bool DeleteAllModel(string CollectionName)
        {
            if (CheckDBLinkState() == false)
            {
                return false;
            }
            bool result = true;
            try
            {
                if (CheckMainDBLinkState())
                {
                    var _collection = _database.GetCollection<BsonDocument>(CollectionName);
                    var Filter = Builders<BsonDocument>.Filter.Eq("ConfigType", "系统配置");
                    var deleteR = _collection.DeleteManyAsync(Filter).Result;
                }
                if (IsContainBackUp)
                {
                    if (CheckBackupDBLinkState())
                    {
                        var _collection = _backupdatabase.GetCollection<BsonDocument>(CollectionName);
                        var Filter = Builders<BsonDocument>.Filter.Eq("ConfigType", "系统配置");
                        var deleteR = _collection.DeleteManyAsync(Filter).Result;
                    }
                }

            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    CheckIsTimeOut(ex.InnerException.Message);
                }
                PublicHelper.WriteErrorMsg(ex, "删除表");

                result = false;
            }
            return result;
        }
        /// <summary>
        /// 删除表中的一个记录
        /// </summary>
        /// <param name="CollectionName"></param>
        /// <param name="DeleteKey"></param>
        /// <param name="DeleteValue"></param>
        /// <returns></returns>
        public static bool DeleteOneModel(string CollectionName, string DeleteKey, object DeleteValue)
        {
            if (CheckDBLinkState() == false)
            {
                return false;
            }
            bool result = true;
            try
            {
                if (CheckMainDBLinkState())
                {
                    var _collection = _database.GetCollection<BsonDocument>(CollectionName);
                    var Filter = Builders<BsonDocument>.Filter.Eq(DeleteKey, DeleteValue);
                    var deleteR = _collection.DeleteManyAsync(Filter).Result;
                }
                if (IsContainBackUp)
                {
                    if (CheckBackupDBLinkState())
                    {
                        var _collection = _backupdatabase.GetCollection<BsonDocument>(CollectionName);
                        var Filter = Builders<BsonDocument>.Filter.Eq(DeleteKey, DeleteValue);
                        var deleteR = _collection.DeleteManyAsync(Filter).Result;
                    }
                }


            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    CheckIsTimeOut(ex.InnerException.Message);
                }
                PublicHelper.WriteErrorMsg(ex, "删除单个模型");

            }
            return result;
        }
        /// <summary>
        /// 删除记录 有大于  等于 小于 符号
        /// </summary>
        /// <param name="CollectionName"></param>
        /// <param name="DeleteKey"></param>
        /// <param name="fuhao"></param>
        /// <param name="DeleteValue"></param>
        /// <returns></returns>
        public static bool DeleteOneModel(string CollectionName, string DeleteKey, string fuhao, string DeleteValue)
        {
            if (CheckDBLinkState() == false)
            {
                return false;
            }
            bool result = true;
            try
            {

                FilterDefinition<BsonDocument> Filter = null;
                switch (fuhao)
                {
                    case "=":
                        Filter = Builders<BsonDocument>.Filter.Eq(DeleteKey, DeleteValue);

                        break;
                    case ">":
                        Filter = Builders<BsonDocument>.Filter.Gt(DeleteKey, int.Parse(DeleteValue));

                        break;
                    case ">=":
                        Filter = Builders<BsonDocument>.Filter.Gte(DeleteKey, int.Parse(DeleteValue));

                        break;
                    case "<=":
                        Filter = Builders<BsonDocument>.Filter.Lte(DeleteKey, int.Parse(DeleteValue));

                        break;
                    case "<":
                        Filter = Builders<BsonDocument>.Filter.Lt(DeleteKey, int.Parse(DeleteValue));

                        break;

                }

                if (CheckMainDBLinkState())
                {
                    var _collection = _database.GetCollection<BsonDocument>(CollectionName);
                    var deleteR = _collection.DeleteManyAsync(Filter);
                    deleteR.Wait();
                }
                if (IsContainBackUp)
                {
                    if (CheckBackupDBLinkState())
                    {
                        var _collection = _backupdatabase.GetCollection<BsonDocument>(CollectionName);
                        var deleteR = _collection.DeleteManyAsync(Filter);
                        deleteR.Wait();
                    }
                }

            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    CheckIsTimeOut(ex.InnerException.Message);
                }
                PublicHelper.WriteErrorMsg(ex, "删除单个模型");

            }
            return result;
        }
        /// <summary>
        /// 清楚历史记录
        /// </summary>
        /// <param name="CollectionName"></param>
        /// <param name="SelectKey"></param>
        /// <param name="deleteTime"></param>
        /// <returns></returns>
        public static bool DeleteHistoryData(string CollectionName, string SelectKey, object deleteTime)
        {
            if (CheckDBLinkState() == false)
            {
                return false;
            }
            bool result = true;
            try
            {
                string deleteWord = "{0:{lte:ISODate('{1}')}}";
                string timeFormat = ((DateTime)deleteTime).AddHours(-8).ToString("yyyy-MM-dd HH:mm:ss.fff");
                timeFormat = string.Format("{0}T{1}+00:00", timeFormat.Split(' ')[0], timeFormat.Split(' ')[1]);
                deleteWord = "{" + SelectKey + ":{$lte:ISODate('" + timeFormat + "')}}";

                if (CheckMainDBLinkState())
                {
                    var _collection = _database.GetCollection<BsonDocument>(CollectionName);
                    var Filter = Builders<BsonDocument>.Filter.Lte(SelectKey, deleteTime);
                    var deleteR = _collection.DeleteMany(deleteWord);
                }
                if (IsContainBackUp)
                {
                    if (CheckBackupDBLinkState())
                    {
                        var _collection = _backupdatabase.GetCollection<BsonDocument>(CollectionName);
                        var Filter = Builders<BsonDocument>.Filter.Lte(SelectKey, deleteTime);
                        var deleteR = _collection.DeleteMany(deleteWord);
                    }
                }


            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    CheckIsTimeOut(ex.InnerException.Message);
                }
                Utility.Helper.PublicHelper.WriteErrorMsg(ex);
                result = false;
            }
            return result;
        }
        #endregion 
        #region Find
        /// <summary>
        /// 加载日志信息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="CollectionName"></param>
        /// <returns></returns>
        public static List<T> FindModelList<T>(string CollectionName) where T : class, new()
        {

            var result = new List<T>();
            var resultTmp = new List<T>();
            if (CheckDBLinkState() == false)
            {
                return result;
            }
            try
            {
                var _collection = _database.GetCollection<BsonDocument>(CollectionName);

                var filter = Builders<BsonDocument>.Filter.Eq("LogType", "inserManyAsync");
                //find one
                var findOne = _collection.Find(new BsonDocument()).FirstOrDefaultAsync();
                //Console.WriteLine(findOne.Result.ToString());
                //find all list
                var findAllList = _collection.Find(new BsonDocument()).ToListAsync();
                //find all list data huge
                _collection.Find(new BsonDocument()).ForEachAsync(x =>
                {
                    var obj = new T();
                    obj = GetModelByDocument<T>(x);
                    result.Add(obj);
                });
                //find Contain condition
                _collection.Find(filter).ForEachAsync(x =>
                {
                    var obj = new T();
                    obj = GetModelByDocument<T>(x);
                    resultTmp.Add(obj);
                });

            }
            catch (Exception ex)
            {
                PublicHelper.WriteErrorMsg(ex, "查询表");

            }
            return result;
        }
        /// <summary>
        /// 目前用于加载系统配置
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="CollectionName"></param>
        /// <returns></returns>
        public static List<T> FindModelListAll<T>(string CollectionName) where T : class, new()
        {
            var result = new List<T>();
            var resultTmp = new List<T>();
            if (CheckDBLinkState() == false)
            {
                return result;
            }
            try
            {

                if (CheckMainDBLinkState())
                {
                    var _collection = _database.GetCollection<BsonDocument>(CollectionName);

                    // var filter = Builders<BsonDocument>.Filter.Eq("LogType", "inserManyAsync");
                    //find one
                    var findOne = _collection.Find(new BsonDocument()).FirstOrDefaultAsync();
                    //Console.WriteLine(findOne.Result.ToString());
                    //find all list
                    var findAllList = _collection.Find(new BsonDocument()).ToListAsync();
                    //find all list data huge
                    var TaskFind = _collection.Find(new BsonDocument()).ForEachAsync(x =>
                    {
                        var obj = new T();
                        obj = GetModelByDocument<T>(x);
                        result.Add(obj);
                    });
                    System.Threading.Thread.Sleep(200);
                    TaskFind.Wait();
                }
                if (IsContainBackUp&& CheckMainDBLinkState()==false)
                {
                    if (CheckBackupDBLinkState())
                    {
                        var _collection = _backupdatabase.GetCollection<BsonDocument>(CollectionName);

                        // var filter = Builders<BsonDocument>.Filter.Eq("LogType", "inserManyAsync");
                        //find one
                        var findOne = _collection.Find(new BsonDocument()).FirstOrDefaultAsync();
                        //Console.WriteLine(findOne.Result.ToString());
                        //find all list
                        var findAllList = _collection.Find(new BsonDocument()).ToListAsync();
                        //find all list data huge
                        var TaskFind = _collection.Find(new BsonDocument()).ForEachAsync(x =>
                        {
                            var obj = new T();
                            obj = GetModelByDocument<T>(x);
                            result.Add(obj);
                        });
                        System.Threading.Thread.Sleep(200);
                        TaskFind.Wait();
                    }
                }
                //find Contain condition
                //_collection.Find(filter).ForEachAsync(x =>
                //{
                //    var obj = new T();
                //    obj = GetModelByDocument<T>(x);
                //    resultTmp.Add(obj);
                //});

            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    CheckIsTimeOut(ex.InnerException.Message);
                }
                PublicHelper.WriteErrorMsg(ex, "查询表");

            }
            return result;
        }
        /// <summary>
        /// 查找一个表的所有数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="CollectionName"></param>
        /// <returns></returns>
        public static ObservableCollection<T> FindModelCol<T>(string CollectionName)
            where T : class, new()
        {
            var result = new ObservableCollection<T>();
            if (CheckDBLinkState() == false)
            {
                return result;
            }
            try
            {
                if (CheckMainDBLinkState())
                {
                    var _collection = _database.GetCollection<BsonDocument>(CollectionName);
                    var TaskFind = _collection.Find(new BsonDocument()).ForEachAsync(x =>
                    {
                        var obj = new T();
                        obj = GetModelByDocument<T>(x);
                        result.Add(obj);
                        //Console.WriteLine(DateTime.Now.ToString("yyyy MM dd HH:mm:ss:fff"));
                    });
                    TaskFind.Wait();
                }
                if (IsContainBackUp && CheckMainDBLinkState() == false)
                {
                    if (CheckBackupDBLinkState())
                    {
                        result = new ObservableCollection<T>();
                        var _collection = _backupdatabase.GetCollection<BsonDocument>(CollectionName);
                        var TaskFind = _collection.Find(new BsonDocument()).ForEachAsync(x =>
                        {
                            var obj = new T();
                            obj = GetModelByDocument<T>(x);
                            result.Add(obj);
                            //Console.WriteLine(DateTime.Now.ToString("yyyy MM dd HH:mm:ss:fff"));
                        });
                        TaskFind.Wait();
                    }
                }

                //find Contain condition
                //_collection.Find(filter).ForEachAsync(x =>
                //{
                //    var obj = new T();
                //    obj = GetModelByDocument<T>(x);
                //    resultTmp.Add(obj);
                //});

            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    CheckIsTimeOut(ex.InnerException.Message);
                }
                //result = null;
                Utility.Helper.PublicHelper.WriteErrorMsg(ex, "查询数据模型集合");
            }
            return result;
        }
        /// <summary>
        /// 查找分区配置的数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="B"></typeparam>
        /// <param name="CollectionName"></param>
        /// <returns></returns>
        public static ObservableCollection<T> FindModelCol<T, B>(string CollectionName) where T : class, new() where B : class, new()
        {
            var result = new ObservableCollection<T>();
            var resultTmp = new ObservableCollection<T>();
            if (CheckDBLinkState() == false)
            {
                return result;
            }
            try
            {

                if (CheckMainDBLinkState())
                {
                    var _collection = _database.GetCollection<BsonDocument>(CollectionName);
                    var TaskFind = _collection.Find(new BsonDocument()).ForEachAsync(x =>
                    {
                        var obj = new T();
                        obj = GetGasMeterConfigByDocument<T, B>(x);
                        result.Add(obj);
                        //Console.WriteLine(DateTime.Now.ToString("yyyy MM dd HH:mm:ss:fff"));
                    });
                    TaskFind.Wait();
                }
                if (IsContainBackUp && CheckMainDBLinkState() == false)
                {
                    if (CheckBackupDBLinkState())
                    {
                        var _collection = _backupdatabase.GetCollection<BsonDocument>(CollectionName);
                        var TaskFind = _collection.Find(new BsonDocument()).ForEachAsync(x =>
                        {
                            var obj = new T();
                            obj = GetGasMeterConfigByDocument<T, B>(x);
                            result.Add(obj);
                            //Console.WriteLine(DateTime.Now.ToString("yyyy MM dd HH:mm:ss:fff"));
                        });
                        TaskFind.Wait();
                    }
                }
                //find Contain condition
                //_collection.Find(filter).ForEachAsync(x =>
                //{
                //    var obj = new T();
                //    obj = GetModelByDocument<T>(x);
                //    resultTmp.Add(obj);
                //});

            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    CheckIsTimeOut(ex.InnerException.Message);
                }
                PublicHelper.WriteErrorMsg(ex, "查找分区数据");
            }
            return result;
        }
        /// <summary>
        /// 查找用户配置数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="B"></typeparam>
        /// <typeparam name="C"></typeparam>
        /// <param name="CollectionName"></param>
        /// <returns></returns>
        public static ObservableCollection<T> FindModelCol<T, B, C>(string CollectionName) where T : class, new() where B : class, new() where C : class, new()
        {
            var result = new ObservableCollection<T>();
            if (CheckDBLinkState() == false)
            {
                return result;
            }
            try
            {

                if (CheckMainDBLinkState())//主服务器
                {
                    var _collection = _database.GetCollection<BsonDocument>(CollectionName);
                    var TaskFind = _collection.Find(new BsonDocument()).ForEachAsync(x =>
                    {
                        var obj = new T();
                        obj = GetGasMeterConfigByDocument<T, B, C>(x);
                        result.Add(obj);
                        //Console.WriteLine(DateTime.Now.ToString("yyyy MM dd HH:mm:ss:fff"));
                    });
                    TaskFind.Wait();
                }
                    if (IsContainBackUp && CheckMainDBLinkState() == false)//备用服务器
                    {
                    if (CheckBackupDBLinkState())
                    {
                        var _collection = _backupdatabase.GetCollection<BsonDocument>(CollectionName);
                        var TaskFind = _collection.Find(new BsonDocument()).ForEachAsync(x =>
                        {
                            var obj = new T();
                            obj = GetGasMeterConfigByDocument<T, B, C>(x);
                            result.Add(obj);
                            //Console.WriteLine(DateTime.Now.ToString("yyyy MM dd HH:mm:ss:fff"));
                        });
                        TaskFind.Wait();
                    }
                }

            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    CheckIsTimeOut(ex.InnerException.Message);
                }
                PublicHelper.WriteErrorMsg(ex, "查找用户数据");
            }
            return result;
        }
        /// <summary>
        /// 查找端口配置
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="CollectionName"></param>
        /// <param name="UpdateKey"></param>
        /// <param name="UpdateValue"></param>
        /// <returns></returns>
        public static ObservableCollection<T> FindModelCol<T>(string CollectionName, string UpdateKey, string UpdateValue) where T : class, new()
        {
            var result = new ObservableCollection<T>();
            if (CheckDBLinkState() == false)
            {
                return result;
            }
            try
            {

                if (CheckMainDBLinkState())//主服务器
                {
                    var _collection = _database.GetCollection<BsonDocument>(CollectionName);
                    var Filter = Builders<BsonDocument>.Filter.Eq(UpdateKey, UpdateValue);
                    var TaskFind = _collection.Find(Filter).ForEachAsync(x =>
                    {
                        var obj = new T();
                        obj = GetModelByDocument<T>(x);
                        result.Add(obj);
                    });
                    TaskFind.Wait();
                }
                if (IsContainBackUp && CheckMainDBLinkState() == false)//备用服务器
                {
                    if (CheckBackupDBLinkState())
                    {
                        var _collection = _backupdatabase.GetCollection<BsonDocument>(CollectionName);
                        var Filter = Builders<BsonDocument>.Filter.Eq(UpdateKey, UpdateValue);
                        var TaskFind = _collection.Find(Filter).ForEachAsync(x =>
                        {
                            var obj = new T();
                            obj = GetModelByDocument<T>(x);
                            result.Add(obj);
                        });
                        TaskFind.Wait();
                    }
                }

            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    CheckIsTimeOut(ex.InnerException.Message);
                }
                PublicHelper.WriteErrorMsg(ex, "查找端口配置");
            }
            return result;
        }
        /// <summary>
        /// 查找告警记录数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="CollectionName"></param>
        /// <param name="selectkeyList"></param>
        /// <param name="selectValueList"></param>
        /// <returns></returns>
        public static ObservableCollection<T> FindModelCol<T>(string CollectionName, List<object> selectkeyList, List<object> selectValueList) where T : class, new()
        {
            var result = new ObservableCollection<T>();
            var resultTmp = new ObservableCollection<T>();
            if (CheckDBLinkState() == false)
            {
                return result;
            }
            try
            {
                string fineword = "";
                //{<key>:{$gte:<value>}} 大于或等于
                //{<key>:{$lte:<value>}} 小于或等于
                for (int i = 0; i < selectValueList.Count; i++)
                {
                    if (selectkeyList[i].ToString() == "StartTime")
                    {
                        var timeFormat = ((DateTime)selectValueList[i]).AddHours(-8).ToString("yyyy-MM-dd HH:mm:ss.fff");
                        timeFormat = string.Format("{0}T{1}+00:00", timeFormat.Split(' ')[0], timeFormat.Split(' ')[1]);
                        fineword = fineword + selectkeyList[i].ToString() + ":{$gte:ISODate('" + timeFormat + "')" + "}";

                    }
                    else if (selectkeyList[i].ToString() == "EndTime")
                    {
                        var timeFormat = ((DateTime)selectValueList[i]).AddHours(-8).ToString("yyyy-MM-dd HH:mm:ss.fff");
                        timeFormat = string.Format("{0}T{1}+00:00", timeFormat.Split(' ')[0], timeFormat.Split(' ')[1]);
                        fineword = fineword + selectkeyList[i].ToString() + ":{$lte:ISODate('" + timeFormat + "')" + "}";

                    }
                    else if (selectkeyList[i].ToString() == "OccurTime")
                    {
                        var timeFormat = ((DateTime)selectValueList[i]).AddHours(-8).ToString("yyyy-MM-dd HH:mm:ss.fff");
                        timeFormat = string.Format("{0}T{1}+00:00", timeFormat.Split(' ')[0], timeFormat.Split(' ')[1]);
                        fineword = fineword + selectkeyList[i].ToString() + ":{$gte:ISODate('" + timeFormat + "')" + "}";

                    }
                    else if (selectValueList[i].GetType() == typeof(int))
                    { 
                        fineword = fineword + selectkeyList[i].ToString() + ":" + selectValueList[i] + "";

                    }
                    else
                    {
                        fineword = fineword + selectkeyList[i].ToString() + ":'" + selectValueList[i] + "'";

                    }
                    if (i != selectValueList.Count - 1)
                    {
                        fineword += ",";
                    }
                    else
                    {
                        fineword = "{" + fineword + "}";
                    }
                }
                SortDefinition<BsonDocument> sortDefinition;
                if (CheckMainDBLinkState())//主服务器
                {
                    var _collection = _database.GetCollection<BsonDocument>(CollectionName);
                    var TaskFind = _collection.Find(fineword).ForEachAsync(x =>
                    {
                        var obj = new T();
                        obj = GetModelByDocument<T>(x);
                        result.Add(obj);
                    });
                    TaskFind.Wait();
                }
                if (IsContainBackUp&& CheckMainDBLinkState()==false)//备用服务器
                {
                    if (CheckBackupDBLinkState())
                    {
                        var _collection = _backupdatabase.GetCollection<BsonDocument>(CollectionName);
                        var TaskFind = _collection.Find(fineword).ForEachAsync(x =>
                        {
                            var obj = new T();
                            obj = GetModelByDocument<T>(x);
                            result.Add(obj);
                        });
                        TaskFind.Wait();
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    CheckIsTimeOut(ex.InnerException.Message);
                }
                PublicHelper.WriteErrorMsg(ex, "查找告警记录");
            }
            return result;
        }
        /// <summary>
        /// 查找浓度查询数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="CollectionName"></param>
        /// <param name="selectkeyList"></param>
        /// <param name="selectValueList"></param>
        /// <returns></returns>
        public static ObservableCollection<T> FindGasPotencyModelCol<T>(string CollectionName, List<object> selectkeyList, List<object> selectValueList) where T : class, new()
        {
            var result = new ObservableCollection<T>();
            if (CheckDBLinkState() == false)
            {
                return result;
            }
            try
            {
                DateTime startTime = new DateTime(2018, 5, 17, 12, 0, 0, DateTimeKind.Utc);
                DateTime endTime = new DateTime(2018, 5, 17, 13, 59, 59, DateTimeKind.Utc);
                string fineword = "";
                //{<key>:{$gte:<value>}} 大于或等于
                //{<key>:{$lte:<value>}} 小于或等于
                for (int i = 0; i < selectValueList.Count; i++)
                {
                    if (selectkeyList[i].ToString() == "StartTime")
                    {
                        var timeFormat = ((DateTime)selectValueList[i]).AddHours(-8).ToString("yyyy-MM-dd HH:mm:ss.fff");
                        timeFormat = string.Format("{0}T{1}+00:00", timeFormat.Split(' ')[0], timeFormat.Split(' ')[1]);
                        fineword = fineword + "OccurTime" + ":{$gte:ISODate('" + timeFormat + "')" + "}";
                        startTime = new DateTime(((DateTime)selectValueList[i]).Year, ((DateTime)selectValueList[i]).Month, ((DateTime)selectValueList[i]).Day, ((DateTime)selectValueList[i]).Hour, ((DateTime)selectValueList[i]).Minute
                            , ((DateTime)selectValueList[i]).Second, DateTimeKind.Utc);
                    }
                    else if (selectkeyList[i].ToString() == "EndTime")
                    {
                        var timeFormat = ((DateTime)selectValueList[i]).AddHours(-8).ToString("yyyy-MM-dd HH:mm:ss.fff");
                        timeFormat = string.Format("{0}T{1}+00:00", timeFormat.Split(' ')[0], timeFormat.Split(' ')[1]);
                        fineword = fineword + "OccurTime" + ":{$lte:ISODate('" + timeFormat + "')" + "}";
                        endTime = new DateTime(((DateTime)selectValueList[i]).Year, ((DateTime)selectValueList[i]).Month, ((DateTime)selectValueList[i]).Day, ((DateTime)selectValueList[i]).Hour, ((DateTime)selectValueList[i]).Minute
              , ((DateTime)selectValueList[i]).Second, DateTimeKind.Utc);
                    }
                    else
                    {
                        fineword = fineword + selectkeyList[i].ToString() + ":'" + selectValueList[i] + "'";

                    }
                    if (i != selectValueList.Count - 1)
                    {
                        fineword += ",";
                    }
                    else
                    {
                        fineword = "{" + fineword + "}";
                    }
                }
                var sorter = Builders<BsonDocument>.Sort;
                var sort = sorter.Ascending("OccurTime");
                //{ OccurTime: {$gte: ISODate('2022-01-06T16:00:00.000+00:00')},OccurTime: {$lte: ISODate('2022-01-07T08:34:00.000+00:00')} }
                var builder = Builders<BsonDocument>.Filter;
                var filter = builder.Gte("OccurTime", startTime.AddHours(-8)) & builder.Lte("OccurTime", endTime.AddHours(-8));


                if (CheckMainDBLinkState())//主服务器
                {
                    var _collection = _database.GetCollection<BsonDocument>(CollectionName);
                    var itemModel = _collection.Find(filter);
                    var TaskFind = _collection.Find(filter).ForEachAsync(x =>
                    {
                        var obj = new T();
                        obj = GetModelByDocument<T>(x);
                        result.Add(obj);
                    });
                    TaskFind.Wait();
                }
                if (IsContainBackUp && CheckMainDBLinkState() == false)//备用服务器
                {
                    if (CheckBackupDBLinkState())
                    {
                        var _collection = _backupdatabase.GetCollection<BsonDocument>(CollectionName);
                        var itemModel = _collection.Find(filter);
                        var TaskFind = _collection.Find(filter).ForEachAsync(x =>
                        {
                            var obj = new T();
                            obj = GetModelByDocument<T>(x);
                            result.Add(obj);
                        });
                        TaskFind.Wait();
                    }
                }

            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    CheckIsTimeOut(ex.InnerException.Message);
                }
                PublicHelper.WriteErrorMsg(ex, "查找浓度信息");
            }
            return result;
        }
        /// <summary>
        /// 查找单个告警记录
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="CollectionName"></param>
        /// <param name="selectkeyList"></param>
        /// <param name="selectValueList"></param>
        /// <returns></returns>
        public static ObservableCollection<T> FindAlarmModelCol<T>(string CollectionName, List<object> selectkeyList, List<object> selectValueList) where T : class, new()
        {
            var result = new ObservableCollection<T>();
            if (CheckDBLinkState() == false)
            {
                return result;
            }
            try
            {
                string fineword = "";

                //{<key>:{$gte:<value>}} 大于或等于
                //{<key>:{$lte:<value>}} 小于或等于
                for (int i = 0; i < selectValueList.Count; i++)
                {
                    if (selectkeyList[i].ToString() == "StartTime")
                    {
                        var timeFormat = ((DateTime)selectValueList[i]).AddHours(-8).ToString("yyyy-MM-dd HH:mm:ss.fff");
                        timeFormat = string.Format("{0}T{1}+00:00", timeFormat.Split(' ')[0], timeFormat.Split(' ')[1]);
                        fineword = fineword + selectkeyList[i].ToString() + ":{$gte:ISODate('" + timeFormat + "')" + "}";

                    }
                    else if (selectkeyList[i].ToString() == "EndTime")
                    {
                        var timeFormat = ((DateTime)selectValueList[i]).AddHours(-8).ToString("yyyy-MM-dd HH:mm:ss.fff");
                        timeFormat = string.Format("{0}T{1}+00:00", timeFormat.Split(' ')[0], timeFormat.Split(' ')[1]);
                        fineword = fineword + selectkeyList[i].ToString() + ":{$lte:ISODate('" + timeFormat + "')" + "}";

                    }
                    else if (selectkeyList[i].ToString() == "GasStatu")
                    {
                        fineword = fineword + selectkeyList[i].ToString() + ":/" + selectValueList[i] + "/" + "";
                    }
                    else
                    {
                        fineword = fineword + selectkeyList[i].ToString() + ":'" + selectValueList[i] + "'";

                    }
                    if (i != selectValueList.Count - 1)
                    {
                        fineword += ",";
                    }
                    else
                    {
                        fineword = "{" + fineword + "}";
                    }
                }
                if (CheckMainDBLinkState())//主服务器
                {
                    var _collection = _database.GetCollection<BsonDocument>(CollectionName);
                    var TaskFind = _collection.Find(fineword).ForEachAsync(x =>
                    {
                        var obj = new T();
                        obj = GetModelByDocument<T>(x);
                        result.Add(obj);
                    });
                    TaskFind.Wait();
                }
                if (IsContainBackUp && CheckMainDBLinkState() == false)//备用服务器
                {
                    if (CheckBackupDBLinkState())
                    {
                        var _collection = _backupdatabase.GetCollection<BsonDocument>(CollectionName);
                        var TaskFind = _collection.Find(fineword).ForEachAsync(x =>
                        {
                            var obj = new T();
                            obj = GetModelByDocument<T>(x);
                            result.Add(obj);
                        });
                        TaskFind.Wait();
                    }
                }

                //find Contain condition
                //_collection.Find(filter).ForEachAsync(x =>
                //{
                //    var obj = new T();
                //    obj = GetModelByDocument<T>(x);
                //    resultTmp.Add(obj);
                //});

            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    CheckIsTimeOut(ex.InnerException.Message);
                }
                PublicHelper.WriteErrorMsg(ex, "查询集合");
            }
            return result;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collectionName"></param>
        /// <param name="selectKey"></param>
        /// <param name="selectValue"></param>
        /// <param name="isDesc"></param>
        /// <param name="descKey"></param>
        /// <returns></returns>
        public static T FindOneModel<T>(string collectionName, string selectKey, string selectValue, bool isDesc, string descKey) where T : class, new()
        {
            if (CheckDBLinkState() == false)
            {
                return null;
            }
            var result = new T();
            try
            {
                var _collection = _database.GetCollection<BsonDocument>(collectionName);
                var sorter = Builders<BsonDocument>.Sort;
                var sort = sorter.Descending(descKey);
                var Filter = Builders<BsonDocument>.Filter.Eq(selectKey, selectValue);
                FindOptions findOptions = new FindOptions();
                var TaskFind = _collection.Find(Filter).Sort(sort).FirstOrDefault();
                if (TaskFind != null)
                {
                    result = GetModelByDocument<T>(TaskFind);

                }
            }
            catch (Exception ex)
            {
                PublicHelper.WriteErrorMsg(ex, "查询单个数据模型");

            }
            return result;
        }
        /// <summary>
        /// 未使用
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collectionName"></param>
        /// <param name="descKey"></param>
        /// <returns></returns>
        public static T FindOneModel<T>(string collectionName, string descKey) where T : class, new()
        {
            if (CheckDBLinkState() == false)
            {
                return null;
            }
            var result = new T();
            try
            {
                var _collection = _database.GetCollection<BsonDocument>(collectionName);
                var sorter = Builders<BsonDocument>.Sort;
                var sort = sorter.Descending(descKey);

                FindOptions findOptions = new FindOptions();
                var TaskFind = _collection.Find(new BsonDocument()).Sort(sort).FirstOrDefault();
                if (TaskFind != null)
                {
                    result = GetModelByDocument<T>(TaskFind);

                }
            }
            catch (Exception ex)
            {
                PublicHelper.WriteErrorMsg(ex, "查询单个数据模型");

            }
            return result;
        }
        /// <summary>
        /// 读取控制器的控制请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collectionName"></param>
        /// <returns></returns>
        public static T FindOneModel<T>(string collectionName) where T : class, new()
        {
            if (CheckDBLinkState() == false)
            {
                return null;
            }
            var result = new T();
            try
            {


                if (CheckMainDBLinkState())//主服务器
                {
                    var _collection = _database.GetCollection<BsonDocument>(collectionName);
                    var sorter = Builders<BsonDocument>.Sort;
                    FindOptions findOptions = new FindOptions();
                    var TaskFind = _collection.Find(new BsonDocument()).FirstOrDefault();
                    if (TaskFind != null)
                    {
                        result = GetModelByDocument<T>(TaskFind);

                    }
                }
                if (IsContainBackUp && CheckMainDBLinkState() == false)//备用服务器
                {
                    if (CheckBackupDBLinkState())
                    {
                        var _collection = _backupdatabase.GetCollection<BsonDocument>(collectionName);
                        var sorter = Builders<BsonDocument>.Sort;
                        FindOptions findOptions = new FindOptions();
                        var TaskFind = _collection.Find(new BsonDocument()).FirstOrDefault();
                        if (TaskFind != null)
                        {
                            result = GetModelByDocument<T>(TaskFind);

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    CheckIsTimeOut(ex.InnerException.Message);
                }
                PublicHelper.WriteErrorMsg(ex, "查询单个数据模型");
            }
            return result;
        }
        /// <summary>
        /// 未使用
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="B"></typeparam>
        /// <param name="collectionName"></param>
        /// <param name="selectKey"></param>
        /// <param name="selectValue"></param>
        /// <returns></returns>
        public static T FindOneModel<T, B>(string collectionName, string selectKey, object selectValue) where T : class, new() where B : class, new()
        {
            if (CheckDBLinkState() == false)
            {
                return null;
            }
            var result = new T();
            try
            {
                var _collection = _database.GetCollection<BsonDocument>(collectionName);
                var Filter = Builders<BsonDocument>.Filter.Eq(selectKey, selectValue);
                FindOptions findOptions = new FindOptions();
                var TaskFind = _collection.Find(Filter).FirstOrDefault();
                if (TaskFind != null)
                {
                    var obj = new T();
                    obj = GetGasMeterConfigByDocument<T, B>(TaskFind);
                    result = obj;
                }
            }
            catch (Exception ex)
            {
                PublicHelper.WriteErrorMsg(ex, "查询单个数据模型");

            }
            return result;
        }
        /// <summary>
        /// 读取用户信息 ，登录
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="B"></typeparam>
        /// <typeparam name="C"></typeparam>
        /// <param name="collectionName"></param>
        /// <param name="selectKey"></param>
        /// <param name="selectValue"></param>
        /// <returns></returns>
        public static T FindOneModel<T, B, C>(string collectionName, string selectKey, object selectValue) where T : class, new() where B : class, new() where C : class, new()
        {
            if (CheckDBLinkState() == false)
            {
                return null;
            }
            var result = new T();
            try
            {

                if (CheckMainDBLinkState())//主服务器
                {
                    var _collection = _database.GetCollection<BsonDocument>(collectionName);
                    var Filter = Builders<BsonDocument>.Filter.Eq(selectKey, selectValue);
                    FindOptions findOptions = new FindOptions();
                    var TaskFind = _collection.Find(Filter).FirstOrDefault();
                    if (TaskFind != null)
                    {
                        var obj = new T();
                        obj = GetGasMeterConfigByDocument<T, B, C>(TaskFind);
                        result = obj;
                    }
                }
                if (IsContainBackUp && CheckMainDBLinkState() == false)//备用服务器
                {
                    if (CheckBackupDBLinkState())
                    {
                        var _collection = _backupdatabase.GetCollection<BsonDocument>(collectionName);
                        var Filter = Builders<BsonDocument>.Filter.Eq(selectKey, selectValue);
                        FindOptions findOptions = new FindOptions();
                        var TaskFind = _collection.Find(Filter).FirstOrDefault();
                        if (TaskFind != null)
                        {
                            var obj = new T();
                            obj = GetGasMeterConfigByDocument<T, B, C>(TaskFind);
                            result = obj;
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    CheckIsTimeOut(ex.InnerException.Message);
                }
                PublicHelper.WriteErrorMsg(ex, "查询用户信息，登录");

            }
            return result;
        }
        /// <summary>
        /// 查找数据分发功能
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collectionName"></param>
        /// <param name="selectKey"></param>
        /// <param name="selectValue"></param>
        /// <returns></returns>
        public static T FindOneModel<T>(string collectionName, string selectKey, object selectValue) where T : class, new()
        {
            if (CheckDBLinkState() == false)
            {
                return null;
            }
            var result = new T();
            try
            {
                if (CheckMainDBLinkState())
                {
                    var _collection = _database.GetCollection<BsonDocument>(collectionName);
                    var Filter = Builders<BsonDocument>.Filter.Eq(selectKey, selectValue);
                    FindOptions findOptions = new FindOptions();
                    var TaskFind = _collection.Find(Filter).FirstOrDefault();
                    if (TaskFind != null)
                    {
                        result = GetModelByDocument<T>(TaskFind);
                    }
                }
                if (IsContainBackUp && CheckMainDBLinkState() == false)
                {
                    if (CheckBackupDBLinkState())
                    {
                        var _collection = _backupdatabase.GetCollection<BsonDocument>(collectionName);
                        var Filter = Builders<BsonDocument>.Filter.Eq(selectKey, selectValue);
                        FindOptions findOptions = new FindOptions();
                        var TaskFind = _collection.Find(Filter).FirstOrDefault();
                        if (TaskFind != null)
                        {
                            result = GetModelByDocument<T>(TaskFind);
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    CheckIsTimeOut(ex.InnerException.Message);
                }
                PublicHelper.WriteErrorMsg(ex, "查询单个数据模型");

            }
            return result;
        }
        /// <summary>
        /// 读取控制器 是否需要消音复位
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collectionName"></param>
        /// <param name="selectKey"></param>
        /// <param name="selectValue"></param>
        /// <param name="doWork"></param>
        /// <returns></returns>
        public static T FindOneModel<T>(string collectionName, string selectKey, object selectValue, string doWork) where T : class, new()
        {
            if (CheckDBLinkState() == false)
            {
                return null;
            }
            var result = new T();
            try
            {

                if (CheckMainDBLinkState())//主服务器
                {
                    var _collection = _database.GetCollection<BsonDocument>(collectionName);
                    var Filter = Builders<BsonDocument>.Filter.Eq(selectKey, selectValue);
                    FindOptions findOptions = new FindOptions();
                    var TaskFind = _collection.Find(Filter).FirstOrDefault();
                    if (TaskFind != null)
                    {
                        result = GetModelByDocument<T>(TaskFind);

                    }
                }
                if (IsContainBackUp && CheckMainDBLinkState() == false)//备用服务器
                {
                    if (CheckBackupDBLinkState())
                    {
                        var _collection = _backupdatabase.GetCollection<BsonDocument>(collectionName);
                        var Filter = Builders<BsonDocument>.Filter.Eq(selectKey, selectValue);
                        FindOptions findOptions = new FindOptions();
                        var TaskFind = _collection.Find(Filter).FirstOrDefault();
                        if (TaskFind != null)
                        {
                            result = GetModelByDocument<T>(TaskFind);

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    CheckIsTimeOut(ex.InnerException.Message);
                }
                PublicHelper.WriteErrorMsg(ex, "查询单个数据模型" + "[" + doWork + "]");

            }
            return result;
        }
        [Obsolete]
        public static long FindCollectionCount(string collectionName)
        {
            long result = 0;
            try
            {
                var _collection = _database.GetCollection<BsonDocument>(collectionName);
                result = _collection.Count(new BsonDocument());

            }
            catch (Exception ex)
            {
                PublicHelper.WriteErrorMsg(ex);
            }
            return result;
        }
        #endregion
        #region UpDate UpdateOneAsync UpdateManyAsync
        /// <summary>
        /// 未使用
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tModel"></param>
        /// <param name="CollectionName"></param>
        /// <param name="UpdateKey"></param>
        /// <param name="UpdateValue"></param>
        /// <returns></returns>
        public bool UpdateCollectionModel<T>(T tModel, string CollectionName, string UpdateKey, string UpdateValue)
        {
            if (CheckDBLinkState() == false)
            {
                return false;
            }
            bool result = true;
            try
            {
                var _collection = _database.GetCollection<BsonDocument>(CollectionName);
                var Filter = Builders<BsonDocument>.Filter.Eq(UpdateKey, UpdateValue);
                var UpdataFilter = Builders<BsonDocument>.Update.Set(UpdateKey, tModel.GetType().GetProperty(UpdateKey).GetValue(tModel, null));
                //批量更新
                //var updated = Builders<BsonDocument>.Update.Inc("counter", 100);
                var updateR = _collection.UpdateOneAsync(Filter, UpdataFilter).Result;
            }
            catch (Exception ex)
            {

            }
            return result;
        }
        #endregion 
        /// <summary>
        /// 未使用
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="CollectionName"></param>
        /// <returns></returns>
        public static bool SelectLogModel<T>(string CollectionName) where T : class, new()
        {
            if (CheckDBLinkState() == false)
            {
                return false;
            }
            bool result = true;
            try
            {
                var collectionTable = _database.GetCollection<BsonDocument>(CollectionName);
                List<T> tmpList = new List<T>();
                collectionTable.Find(new BsonDocument()).ForEachAsync(x =>
                {
                    var obj = new T();
                    obj = GetModelByDocument<T>(x);
                    tmpList.Add(obj);
                });

                //var filter = Builders<BsonDocument>.Filter.Eq("counter", 71);
                //var document = collection.Find(filter).FirstAsync().Result;
                //Console.WriteLine(document);
            }
            catch (Exception ex)
            {

            }
            return result;
        }
        public static bool SelectLogModel<T>(string CollectionName, string conditionKey, string conditionValue)
        {
            if (CheckDBLinkState() == false)
            {
                return false;
            }
            bool result = true;
            try
            {
                var collectionTable = _database.GetCollection<BsonDocument>(CollectionName);
                // var findCollection = collectionTable.Find(new BsonDocument()).Any().Result;

                var filter = Builders<BsonDocument>.Filter.Eq("LogType", "检索标志");
                BsonDocument condition = new BsonDocument
                {
                    { conditionKey, conditionValue },
                    { "LogReMark", "{[$lt:15]}" }
                };

                var document = collectionTable.Find(condition).ToList();
                //var document = collection.Find(filter).FirstAsync().Result;
                Console.WriteLine(document);
            }
            catch (Exception ex)
            {

            }
            return result;
        }
        public static bool DeleteModel<T>(string CollectionName)
        {
            if (CheckDBLinkState() == false)
            {
                return false;
            }
            bool result = true;
            try
            {

            }
            catch (Exception ex)
            {

            }
            return result;
        }
        /// <summary>
        /// 更新数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="CollectionName"></param>
        /// <param name="selectkeyList"></param>
        /// <param name="selectValueList"></param>
        /// <param name="insertkeyList"></param>
        /// <param name="inservalueList"></param>
        /// <returns></returns>
        public static bool UpDateModel<T>(string CollectionName, List<object> selectkeyList, List<object> selectValueList,
                                            List<object> insertkeyList, List<object> inservalueList)
        {
            if (CheckDBLinkState() == false)
            {
                return false;
            }
            bool result = true;
            try
            {
                string fineword = "";
                var updateOptions = new UpdateOptions { IsUpsert = true };
                //{GasmeterId:'GT2014',StartTime:ISODate('2021-12-22T19:27:02.000+00:00'),KeepingTime:''}
                for (int i = 0; i < selectValueList.Count; i++)
                {
                    if (typeof(DateTime).IsAssignableFrom(selectValueList[i].GetType()))
                    {
                        var timeFormat = ((DateTime)selectValueList[i]).AddHours(-8).ToString("yyyy-MM-dd HH:mm:ss.fff");
                        timeFormat = string.Format("{0}T{1}+00:00", timeFormat.Split(' ')[0], timeFormat.Split(' ')[1]);
                        fineword = fineword + selectkeyList[i].ToString() + ":ISODate('" + timeFormat + "')";
                    }
                    else if (typeof(int).IsAssignableFrom(selectValueList[i].GetType()))
                    {
                        fineword = fineword + selectkeyList[i].ToString() + ":" + selectValueList[i] + "";

                    }
                    else
                    {
                        fineword = fineword + selectkeyList[i].ToString() + ":'" + selectValueList[i] + "'";

                    }
                    if (i != selectValueList.Count - 1)
                    {
                        fineword += ",";
                    }
                    else
                    {
                        fineword = "{" + fineword + "}";
                    }
                }


                if (CheckMainDBLinkState())//主服务器
                {
                    var collectionTable = _database.GetCollection<BsonDocument>(CollectionName);
                    for (int i = 0; i < insertkeyList.Count; i++)
                    {
                        if (typeof(DateTime).IsAssignableFrom(inservalueList[i].GetType()))
                        {
                            var updater = Builders<BsonDocument>.Update.Set(insertkeyList[i].ToString(), (DateTime)inservalueList[i]);
                            var taskResult = collectionTable.UpdateOneAsync(fineword, updater, updateOptions);
                        }
                        else
                        {
                            var updater = Builders<BsonDocument>.Update.Set(insertkeyList[i].ToString(), inservalueList[i]);
                            var taskResult = collectionTable.UpdateOneAsync(fineword, updater, updateOptions);
                            taskResult.Wait();
                        }

                    }
                }
                if (IsContainBackUp)//备用服务器
                {
                    if (CheckBackupDBLinkState())
                    {
                        var collectionTable = _backupdatabase.GetCollection<BsonDocument>(CollectionName);
                        for (int i = 0; i < insertkeyList.Count; i++)
                        {
                            if (typeof(DateTime).IsAssignableFrom(inservalueList[i].GetType()))
                            {
                                var updater = Builders<BsonDocument>.Update.Set(insertkeyList[i].ToString(), (DateTime)inservalueList[i]);
                                var taskResult = collectionTable.UpdateOneAsync(fineword, updater, updateOptions);
                            }
                            else
                            {
                                var updater = Builders<BsonDocument>.Update.Set(insertkeyList[i].ToString(), inservalueList[i]);
                                var taskResult = collectionTable.UpdateOneAsync(fineword, updater, updateOptions);
                                taskResult.Wait();
                            }

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    CheckIsTimeOut(ex.InnerException.Message);
                }
                Helper.PublicHelper.WriteErrorMsg(ex);
            }
            return result;
        }
        /// <summary>
        /// 未使用
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="CollectionName"></param>
        /// <param name="selectkeyList"></param>
        /// <param name="selectValueList"></param>
        /// <param name="insertkeyList"></param>
        /// <param name="inservalueList"></param>
        /// <returns></returns>
        public static bool FindOneAndUpdateModel<T>(string CollectionName, List<object> selectkeyList, List<object> selectValueList,
                                           List<object> insertkeyList, List<object> inservalueList)
        {
            if (CheckDBLinkState() == false)
            {
                return false;
            }
            bool result = true;
            try
            {
                var collectionTable = _database.GetCollection<BsonDocument>(CollectionName);
                string fineword = "";
                var updateOptions = new UpdateOptions { IsUpsert = true };
                //{GasmeterId:'GT2014',StartTime:ISODate('2021-12-22T19:27:02.000+00:00'),KeepingTime:''}
                for (int i = 0; i < selectValueList.Count; i++)
                {
                    if (typeof(DateTime).IsAssignableFrom(selectValueList[i].GetType()))
                    {
                        var timeFormat = ((DateTime)selectValueList[i]).AddHours(-8).ToString("yyyy-MM-dd HH:mm:ss.fff");
                        timeFormat = string.Format("{0}T{1}+00:00", timeFormat.Split(' ')[0], timeFormat.Split(' ')[1]);
                        fineword = fineword + selectkeyList[i].ToString() + ":ISODate('" + timeFormat + "')";
                    }
                    else if (typeof(int).IsAssignableFrom(selectValueList[i].GetType()))
                    {
                        fineword = fineword + selectkeyList[i].ToString() + ":" + selectValueList[i] + "";

                    }
                    else
                    {
                        fineword = fineword + selectkeyList[i].ToString() + ":'" + selectValueList[i] + "'";

                    }
                    if (i != selectValueList.Count - 1)
                    {
                        fineword += ",";
                    }
                    else
                    {
                        fineword = "{" + fineword + "}";
                    }
                }
                for (int i = 0; i < insertkeyList.Count; i++)
                {
                    if (typeof(DateTime).IsAssignableFrom(inservalueList[i].GetType()))
                    {
                        var updater = Builders<BsonDocument>.Update.Set(insertkeyList[i].ToString(), (DateTime)inservalueList[i]);
                        var taskResult = collectionTable.UpdateOneAsync(fineword, updater, updateOptions);
                    }
                    else
                    {
                        var updater = Builders<BsonDocument>.Update.Set(insertkeyList[i].ToString(), inservalueList[i]);
                        var taskResult = collectionTable.UpdateOneAsync(fineword, updater, updateOptions);
                    }

                }

            }
            catch (Exception ex)
            {

            }
            return result;
        }
        public static T GetModelByDocument<T>(BsonDocument doc) where T : class, new()
        {
            var obj = new T();
            Type t = obj.GetType();
            PropertyInfo[] perty = t.GetProperties();
            foreach (var k in perty)
            {
                if (doc.Contains(k.Name) && doc[k.Name].IsBsonNull == false)
                {
                    try
                    {
                        object tmpobject = ChangeType(doc[k.Name], k.PropertyType);
                        obj.GetType().GetProperty(k.Name).SetValue(obj, ChangeType(doc[k.Name], k.PropertyType), null);

                    }
                    catch (Exception ex)
                    {
                        var tempModel = doc[k.Name];
                        obj.GetType().GetProperty(k.Name).SetValue(obj, null, null);
                    }
                }
            }
            return obj;
        }
        public static T GetGasMeterConfigByDocument<T, B>(BsonDocument doc) where T : class, new() where B : class, new()
        {

            var obj = new T();
            var obj2 = new B();
            Type t = obj.GetType();
            Type t2 = obj2.GetType();

            PropertyInfo[] perty = t.GetProperties();
            foreach (var k in perty)
            {
                if (doc.Contains(k.Name) && doc[k.Name].IsBsonNull == false)
                {
                    try
                    {
                        if (k.Name == "ChildAreaModels")
                        {

                            BsonValue TmpModel = doc[k.Name];


                            ObservableCollection<B> _bColle = new ObservableCollection<B>();

                            foreach (var j in TmpModel.AsBsonArray)
                            {
                                Console.WriteLine(j);
                                obj2 = new B();
                                foreach (var w in t2.GetProperties())
                                {
                                    try
                                    {

                                        obj2.GetType().GetProperty(w.Name).SetValue(obj2, ChangeType(j[w.Name], w.PropertyType), null);

                                    }
                                    catch (Exception ex)
                                    {
                                        //obj2.GetType().GetProperty(w.Name).SetValue(obj2, null, null);

                                    }
                                }
                                _bColle.Add(obj2);
                            }

                            obj.GetType().GetProperty(k.Name).SetValue(obj, _bColle, null);



                        }
                        else
                        {
                            obj.GetType().GetProperty(k.Name).SetValue(obj, ChangeType(doc[k.Name], k.PropertyType), null);

                        }
                        //obj.GetType().GetProperty(k.Name).SetValue(obj, ChangeType(doc[k.Name], k.PropertyType), null);
                    }
                    catch (Exception ex)
                    {
                        obj.GetType().GetProperty(k.Name).SetValue(obj, null, null);
                    }
                }
            }
            return obj;
        }
        public static T GetGasMeterConfigByDocument<T, B, C>(BsonDocument doc) where T : class, new() where B : class, new() where C : class, new()
        {

            var obj = new T();
            var obj2 = new B();
            var obj3 = new C();
            Type t = obj.GetType();
            Type t2 = obj2.GetType();
            Type t3 = obj3.GetType();

            PropertyInfo[] perty = t.GetProperties();
            foreach (var k in perty)
            {
                if (doc.Contains(k.Name) && doc[k.Name].IsBsonNull == false)
                {
                    try
                    {
                        if (k.Name == "ChildAreaModels")
                        {

                            BsonValue TmpModel = doc[k.Name];
                            ObservableCollection<B> _bColle = new ObservableCollection<B>();
                            foreach (var j in TmpModel.AsBsonArray)
                            {
                                Console.WriteLine(j);
                                obj2 = new B();
                                foreach (var w in t2.GetProperties())
                                {
                                    try
                                    {
                                        obj2.GetType().GetProperty(w.Name).SetValue(obj2, ChangeType(j[w.Name], w.PropertyType), null);

                                    }
                                    catch (Exception ex)
                                    {
                                        obj2.GetType().GetProperty(w.Name).SetValue(obj2, null, null);

                                    }
                                }
                                _bColle.Add(obj2);
                            }
                            obj.GetType().GetProperty(k.Name).SetValue(obj, _bColle, null);
                        }
                        else if (k.Name == "BindingAreaModels")
                        {
                            BsonValue TmpModel = doc[k.Name];
                            List<C> _bColle = new List<C>();
                            foreach (var j in TmpModel.AsBsonArray)
                            {
                                Console.WriteLine(j);
                                obj3 = new C();
                                foreach (var w in t3.GetProperties())
                                {
                                    try
                                    {
                                        obj3.GetType().GetProperty(w.Name).SetValue(obj3, ChangeType(j[w.Name], w.PropertyType), null);

                                    }
                                    catch (Exception ex)
                                    {
                                        obj3.GetType().GetProperty(w.Name).SetValue(obj3, null, null);

                                    }
                                }
                                _bColle.Add(obj3);
                            }
                            obj.GetType().GetProperty(k.Name).SetValue(obj, _bColle, null);
                        }
                        else if (k.Name == "ClientAdminModel")
                        {
                            //MongoDB.Bson.BsonDocument
                            BsonValue TmpModel = doc[k.Name];
                            var j = TmpModel;
                            obj2 = new B();
                            foreach (var w in t2.GetProperties())
                            {
                                try
                                {
                                    obj2.GetType().GetProperty(w.Name).SetValue(obj2, ChangeType(j[w.Name], w.PropertyType), null);

                                }
                                catch (Exception ex)
                                {
                                    obj2.GetType().GetProperty(w.Name).SetValue(obj2, null, null);

                                }
                            }
                            obj.GetType().GetProperty(k.Name).SetValue(obj, obj2, null);
                        }
                        else
                        {
                            obj.GetType().GetProperty(k.Name).SetValue(obj, ChangeType(doc[k.Name], k.PropertyType), null);

                        }
                        //obj.GetType().GetProperty(k.Name).SetValue(obj, ChangeType(doc[k.Name], k.PropertyType), null);
                    }
                    catch (Exception ex)
                    {
                        obj.GetType().GetProperty(k.Name).SetValue(obj, null, null);
                    }
                }
            }
            return obj;
        }
        #region  ChangeType
        private static object ChangeType(object itemValue, Type itemType)
        {
            return ChangeType(itemValue, itemType, System.Threading.Thread.CurrentThread.CurrentCulture);
        }
        private static object ChangeType(object obj, Type conversionType, IFormatProvider provider)
        {
            #region Nullable
            Type nullableType = Nullable.GetUnderlyingType(conversionType);
            if (nullableType != null)
            {
                if (obj == null)
                {
                    return null;
                }
                return Convert.ChangeType(obj, nullableType, provider);
            }
            #endregion
            try
            {

                //Enum
                if (typeof(System.Enum).IsAssignableFrom(conversionType))
                {
                    return System.Enum.Parse(conversionType, obj.ToString());
                }
                //Double
                else if (typeof(Double).IsAssignableFrom(conversionType))
                {
                    return Convert.ToDouble(obj);
                }
                //DateTime
                else if (typeof(DateTime).IsAssignableFrom(conversionType))
                {
                    return Convert.ToDateTime(obj).ToLocalTime();
                }
                else if (typeof(String).IsAssignableFrom(conversionType))
                {
                    if (obj == BsonNull.Value)
                    {
                        return "";
                    }
                    else
                    {
                        return Convert.ToString(obj);
                    }

                }
                else if (typeof(Int32).IsAssignableFrom(conversionType))
                {

                    if (obj == BsonNull.Value)
                    {
                        return 0;
                    }
                    else
                    {
                        return Convert.ToInt32(obj);
                    }

                }
                else if (typeof(bool).IsAssignableFrom(conversionType))
                {
                    return Convert.ToBoolean(obj);
                }
                else if (typeof(List<string>).IsAssignableFrom(conversionType))
                {
                    List<string> tmpList = new List<string>();
                    if (obj != null)
                    {
                        BsonArray tp = obj as BsonArray;
                        foreach (var k in tp)
                        {
                            tmpList.Add(k.ToString());
                        }
                    }

                    return tmpList;
                }
                else if (typeof(Utility.DataEnum.Enum_UserLevel).IsAssignableFrom(conversionType))
                {
                    return (Utility.DataEnum.Enum_UserLevel)(obj);
                }
                else
                {
                    return null;
                }

                //Other
            }
            catch (Exception ex)
            {

            }
            return Convert.ChangeType(obj, nullableType, provider);

        }
        #endregion
        #region Function
        /// <summary>
        /// 删除数据表
        /// </summary>
        /// <param name="collectionName"></param>
        /// <returns></returns>
        public static bool DropCollection(string collectionName)
        {
            if (CheckDBLinkState() == false)
            {
                return false;
            }
            bool result = true;
            try
            {
                //var collectionTable = _database.GetCollection<BsonDocument>(CollectionName);
                if (CheckMainDBLinkState())//主服务器
                {
                    _database.DropCollection(collectionName);

                }
                if (IsContainBackUp)//备用服务器
                {
                    if (CheckBackupDBLinkState())
                    {
                        _backupdatabase.DropCollection(collectionName);

                    }
                }
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    CheckIsTimeOut(ex.InnerException.Message);
                }
                Utility.Helper.PublicHelper.WriteErrorMsg(ex);
                result = false;
            }
            return result;

        }
        public static bool UpDateRealTimePotencyData(string serialNo, string gasValue, string gasErrorFlag, string GasState)
        {
            if (CheckDBLinkState() == false)
            {
                return false;
            }
            bool result = true;
            try
            {

            }
            catch (Exception ex)
            {
                Utility.Helper.PublicHelper.WriteErrorMsg(ex);
                result = false;
            }
            return result;
        }
        public void SaveGasMeterRealTimeValue()
        {

        }
        public void SaveGasMeterAlarmRecord()
        {

        }
        /// <summary>
        /// 检查连接数据库是否超时
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static bool CheckIsTimeOut(string msg)
        {
            bool result = false;
            if (msg.Contains("timeout"))
            {
                PublicHelper.WriteErrorMsg("数据库连接超时");

                //情况一 ：主服务器运行中
                Const.GbUnit.DatabaseLinkSuccessFlag = false;
                Utility.Const.GbUnit.reloadRealTimeModelFlag = true;
                //更新服务器状态
                if (IsContainBackUp)
                {
                    //采用备用服务器
                    //情况二:备用服务器运行中
                    //Const.GbUnit.BackupDatabaseLinkSuccessFlag = false;
                }


            }
            else
            {


            }

            return result;
        }
        #endregion
    }
}
